package user.controller;


import com.alibaba.fastjson.JSON;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import commons.IdNumNameCheck;
import commons.SmsUtils;
import entity.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import user.mapper.CreditCardTpyeMapper;
import user.mapper.TContactsMapper;
import user.mapper.TEssentialMapper;
import user.mapper.TUnitinfortionMapper;
import user.service.ICardProgressService;
import user.service.ICreditCardTypeService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Type;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 申请信用卡相关模块
 * </p>
 *
 * @author liso
 * @since 2020/10/14 18:00
 */
@Api(tags = "申请信用卡相关模块")
@Transactional
@Controller
@RequestMapping("/shenqin")
public class ApplyController {

    //去办卡页面
    @ApiOperation(value = "去办卡页面")
    @GetMapping("/tobankashenqing")
    public String toBanka() {
        return "bankashenqing";
    }

    //去信息填写页面
    @ApiOperation(value = "去信息填写页面")
    @GetMapping("/tojibenxinxi")
    public String toJiebnxinxi() {
        return "jibenxinxi";
    }


    //去result页面
    @ApiOperation(value = "去result页面")
    @GetMapping("/toresult")
    public String toresult(String data, Model model) {
        System.out.println("来了");
        System.out.println(data);
        model.addAttribute("resul", data);
        return "applyresult";
    }


    @Autowired
    private TEssentialMapper tEssentialMapper;
    @Autowired
    private TUnitinfortionMapper tUnitinfortionMapper;
    @Autowired
    private TContactsMapper tContactsMapper;
    @Autowired
    private StringRedisTemplate template;
    @Autowired
    private ICardProgressService iCardProgressService;
    @Autowired
    private ICreditCardTypeService iCreditCardTypeService;

    /**
     * <p>
     * 发送手机验证码
     * </p>
     *
     * @author liso
     * @since 2020/10/14 17:54
     * * @param number
     * * @param session
     * * @return boolean
     */
    @ApiOperation(value = "发送手机验证码", notes = "尝试向已登录用户填写的号码发送验证码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "number", value = "手机号码", required = true, paramType = "query"),
            @ApiImplicitParam(name = "session", value = "会话对象", required = true, paramType = "query", dataType
                    = "HttpSession")
    })
    @GetMapping("/sendcode")
    @ResponseBody
    public boolean sendcode(String number, HttpSession session) {
        int code = 123456;
        Object userid = session.getAttribute("userid");

        if (userid == null) {
            return false;
        }

        template.opsForHash().put(userid.toString(), Integer.toString(code), "true");
        template.expire(userid.toString(), 15, TimeUnit.MINUTES);
//        try {
//            SendSmsResponse sendSmsResponse = SmsUtils.sendSms(number, code + "");// TODO 填写你需要测试的手机号码
//            if (sendSmsResponse.getCode().equals("OK")) {
//                return true;
//            }
//        } catch (ClientException e) {
//            e.printStackTrace();
//        }

        return true;
    }


    //时间紧 没对方法做解耦优化 估计后面也不会补上 因为不好使
    private static Object jsonobject(Object o) {
        String string = JSON.toJSONString(o);
        TContacts tContacts = JSON.parseObject(string, (Type) o.toString().getClass());
        return null;
    }

    /**
     * <p>
     * 申请卡片信息校验与录入
     * </p>
     * <p>
     * * @param datamap
     * * @param session
     *
     * @return java.lang.String
     * @author liso
     * @since 2020/10/11 21:26
     */
    @ApiOperation(value = "申请卡片信息校验与录入", notes = "申请信用卡的三张表的信息在这里验证提交,同时生成申请进程对象")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "datamap", value = "申请数据", required = true, paramType = "query", dataType =
                    "HttpServletRequest"),
            @ApiImplicitParam(name = "request", value = "请求对象", required = true, paramType = "query", dataType =
                    "Map<String, Object>")
    })
    @PostMapping("/submit")
    @ResponseBody
    public String applyInfor(@RequestBody Map<String, Object> datamap, HttpServletRequest request) {
        if (datamap.isEmpty()) {
            return "咩有数据";
        }

        // 拿到验证码
        Object code = datamap.get("code");
        if (code==null) {
            return "没有验证码";
        }
        Object typeid = datamap.get("typeid");
        if (typeid==null) {
            return "没有选择卡的类型";
        }

        // 获取联系人对象
        Object contact1 = datamap.get("contact");
        String string = JSON.toJSONString(contact1);
        TContacts tContacts = JSON.parseObject(string, TContacts.class);
        if (tContacts==null) {
            return "没有联系人信息";
        }
        //获取单位信息对象
        Object unitinfortion1 = datamap.get("unitinfortion");
        String string1 = JSON.toJSONString(unitinfortion1);
        TUnitinfortion unitinfortion = JSON.parseObject(string1, TUnitinfortion.class);
        if (unitinfortion==null) {
            return "没有单位信息";
        }
        //获取基本信息对象
        Object essential1 = datamap.get("essential");
        String string2 = JSON.toJSONString(essential1);
        TEssential essential = JSON.parseObject(string2, TEssential.class);
        if (essential==null) {
            return "没有基本信息";
        }

        String identityId = essential.getIdentityid(); //拿到身份证号
        String phonenumber = essential.getPhonenumber(); //拿到手机号
        String realname = essential.getRealname(); // 拿到姓名

        if (identityId != null && phonenumber != null && realname != null) {
            //  用户id
            Object userid = request.getSession().getAttribute("userid");
            //  验证验证码
            Object user = template.opsForHash().get(userid.toString(), code);
            if (user == null) {
                return "验证码不正确";
            }


//            //这部分是借口的调用可以判断信息的真实性
//            boolean check = IdNumNameCheck.check(identityId, phonenumber, realname);
//            System.out.println(check);


            //为了保证测试可以顺利进行 结果为百分百通过
            if (true) {
                Integer userId = Integer.valueOf(userid.toString());
                //插入删除都直接在这写 底层的实现就是这句话 要增强的时候再建dao层吧
                essential.setUserId(userId);
                tEssentialMapper.insert(essential);
                Integer essentialid = essential.getEssentialid();

                tContacts.setUserId(userId);
                tContactsMapper.insert(tContacts);
                Integer contactId = tContacts.getContactId();

                unitinfortion.setUserId(userId);
                tUnitinfortionMapper.insert(unitinfortion);
                Integer uid = unitinfortion.getUid();

                //  分别拿到三张表的id 创建对象 然后把他们插入到申请表
                System.out.println(essentialid + "||" + contactId + "||" + uid);
                CardProgress cardProgress = new CardProgress();
                //三张表和类型的id
                cardProgress.setContactId(contactId);
                cardProgress.setEssentialid(essentialid);
                cardProgress.setUid(uid);

                //获取到卡类型 这个表的字段大都是唯一的 后面可以使用name做查询条件

                CcmsCreditcardtype ccmsCreditcardtype = iCreditCardTypeService.getTypeById(Integer.parseInt(typeid
                        .toString()));
                cardProgress.setCreditType(ccmsCreditcardtype.getTypename());

                // 创建的人和时间以及初始状态
                cardProgress.setCpCreateTime(new java.sql.Date(System.currentTimeMillis()));
                cardProgress.setCpCreateUserid(Integer.parseInt(userid.toString()));
                cardProgress.setCpStatus("申请中");

                iCardProgressService.insertProgress(cardProgress);
                return "good";
            }

        }

        return "信息不完整或格式不正确";
    }

}
